package org.academy.funfair.dbchecker;

import javax.sql.DataSource;

import org.academy.funfair.FunfairProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnBean(DataSource.class)
public final class DbChecker implements CommandLineRunner {

	@Autowired
	private JdbcTemplate template;

	@Override
	public void run(String... arg0) throws Exception {
		checkProfile();
		checkVersion();
	}

	private void checkProfile() throws Exception {
		final int rows = template.queryForObject(
				"select count(*) from funfair_sys_config where app_name = ? and property_name = 'profile' and property_value = ?",
				new Object[] { FunfairProperties.getName(), FunfairProperties.getProfile() },
				Integer.class).intValue();

		if (rows == 0) {
			throw new Exception("Database profile is inconsistent with system profile.");
		}
	}

	private void checkVersion() throws Exception {
		final int rows = template.queryForObject(
				"select count(*) from funfair_sys_config where app_name = ? and property_name = 'version' and property_value = ?",
				new Object[] { FunfairProperties.getName(), FunfairProperties.getVersion() },
				Integer.class).intValue();

		if (rows == 0) {
			throw new Exception("Database version is inconsistent with system version.");
		}
	}

}
